// const BASE_URL = 'http://api-breakingnews-web.itheima.net'
// 切换注册登录
$('#goto-register').on('click', function () {
  $('#register').stop().show()
})
$('#goto-login').on('click', function () {
  $('#register').stop().hide()
})

// 验证
layui.form.verify({
  username: value => {
    //value：表单的值、item：表单的DOM对象
    if (!/^[a-z0-9]{6,10}$/.test(value)) {
      return '账号名是6到10位由数字, 小写字母组成'
    }
  },
  password: value => {
    if (!/^[\S]{6,10}$/.test(value)) {
      return '密码是6到10位, 不能有空格'
    }
  },
  repwd: value => {
    if ($('.pwd').val() != value) {
      return '两次密码不相同'
    }
  }
})

// 注册提交
$('#register .layui-form').on('submit', function (e) {
  e.preventDefault()
  let data = $('#register form').serialize()

  myRegister(data, res => {
    let { status, message } = res.data
    if (status === 0) {
      successMsg(message, () => {
        $('#register').stop().hide()
      })
    } else {
      errorMsg(message, () => {
        $('#register form')[0].reset()
      })
    }
  })
})

// 登录提交
$('#login form').on('submit', function (e) {
  e.preventDefault()

  let data = $('#login form').serialize()
  myLogin(data, res => {
    let { status, message } = res.data
    if (status === 0) {
      localStorage.setItem('token', res.data.token)
      successMsg(message, () => {
        location.href = '/index.html'
      })
    } else {
      errorMsg(message, () => {
        $('#login form')[0].reset()
      })
    }
  })
})
